package com.itshen.service.impl;


import com.itshen.domain.User;
import com.itshen.domain.UserLoginDTO;
import com.itshen.domain.UserRegisterDTO;
import com.itshen.exception.PasswordErrorException;
import com.itshen.mapper.UserMapper;
import com.itshen.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * 用户相关接口
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);

        //密码比对
        //对前端传过来的明文密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException("PASSWORD_ERROR");
        }
        return user;
    }

    @Override
    public void insert(UserRegisterDTO userRegisterDTO) {
        String username = userRegisterDTO.getUsername();
        String password = userRegisterDTO.getPassword();
        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
         userMapper.insert(username,password);
    }
}
